<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\PopularScienceMagazine as PopularScienceMagazinemodel;
use think\Request;

class Popular extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 获取科普杂志列表（支持多条件筛选）
     * @param Request $request
     * @return \think\Response
     */
    public function index(Request $request)
    {
        // 获取请求参数
        $params = $request->param();
        $page = $request->param('page', 1, 'intval');
        $limit = $request->param('limit', 10, 'intval');

        // 构建查询条件
        $where = [];

        // 标题模糊查询
        if (!empty($params['title'])) {
            $where[] = ['title', 'like', "%{$params['title']}%"];
        }

        // 价格范围筛选
        if (!empty($params['min_price'])) {
            $where[] = ['price', '>=', $params['min_price']];
        }
        if (!empty($params['max_price'])) {
            $where[] = ['price', '<=', $params['max_price']];
        }

        // 折扣筛选（price < old_price）
        if (isset($params['is_discount']) && $params['is_discount'] == 1) {
            $where[] = ['price', '<', db()->raw('old_price')];
        }

        // 即将结束筛选（end_time在7天内）
        if (isset($params['ending_soon']) && $params['ending_soon'] == 1) {
            $where[] = ['end_time', 'between', [date('Y-m-d'), date('Y-m-d', strtotime('+7 days'))]];
        }

        // 排序处理
        $order = 'id DESC';
        if (!empty($params['sort_field']) && !empty($params['sort_order'])) {
            $order = "{$params['sort_field']} {$params['sort_order']}";
        }

        // 查询数据
        $list = PopularScienceMagazinemodel::where($where)
            ->order($order)
            ->paginate([
                'list_rows' => $limit,
                'page' => $page,
            ]);

        // 处理封面图片为完整URL
        $list->each(function($item) {
            if (!empty($item['cover_image'])) {
                $item['cover_image_url'] = $this->getFullImageUrl($item['cover_image']);
            }
            // 计算折扣率
            if ($item['old_price'] > 0) {
                $item['discount_rate'] = round(($item['price'] / $item['old_price']) * 10, 1);
            }
            return $item;
        });

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => [
                'list' => $list->items(),
                'total' => $list->total(),
                'current_page' => $list->currentPage(),
                'last_page' => $list->lastPage()
            ]
        ]);
    }

    /**
     * 获取图片完整URL
     * @param string $imagePath 图片路径
     * @return string
     */
    protected function getFullImageUrl($imagePath)
    {
        // 这里需要根据您的实际域名配置进行调整
        $baseUrl = config('app.domain') ?: $this->request->domain();
        return $baseUrl . '/' . ltrim($imagePath, '/');
    }

    /**
     * 获取科普杂志详情
     * @return \think\Response
     */
    public function detail(Request $request): \think\Response
    {
        $id = $request->param('id', 0, 'intval');
        // 验证ID参数
        if (!is_numeric($id) || $id <= 0) {
            return json([
                'code' => 400,
                'msg' => '参数错误',
                'data' => null
            ]);
        }

        // 查询数据
        $magazine = PopularScienceMagazinemodel::find($id);

        if (!$magazine) {
            return json([
                'code' => 404,
                'msg' => '杂志不存在',
                'data' => null
            ]);
        }

        // 处理图片为完整URL
        if (!empty($magazine['cover_image'])) {
            $magazine['cover_image_url'] = $this->getFullImageUrl($magazine['cover_image']);
        }

        // 计算折扣率
        if ($magazine['old_price'] > 0) {
            $magazine['discount_rate'] = round(($magazine['price'] / $magazine['old_price']) * 10, 1);
        }

        return json([
            'code' => 200,
            'msg' => 'success',
            'data' => $magazine
        ]);
    }


}